<script setup>
import { ref, onMounted,reactive} from 'vue'
import {ElMessage,ElMessageBox} from "element-plus";
import {} from "@/api/article.js";
import {
  addArticleCategory,
  deleteArticleCategory,
  queryAllArticleCategory,
  updateArticleCategory
} from "@/api/articleCategory.js";

const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true);
const total = ref(0);
const tableData = ref([])
const formInline =ref({
  categoryName: ''
});
// 对话框控制
const dialogVisible = ref(false)
const mode = ref('add') // add/edit/view
const formData = ref({
  id: null,
  categoryName: '',
  createTime: ''
})
// 添加选中的行数据
const selectedRows = ref([]);

// 表单验证规则
const formRules = reactive({
  categoryName: [{ required: true, message: '请输入文章类型', trigger: 'blur' }]
})

onMounted(() => {
  search();
})
const search=async ()=>{
  const restult = await queryAllArticleCategory(currentPage.value,pageSize.value,formInline.value.categoryName)
  console.log(restult)
  if(restult.code){
    tableData.value = restult.data.rows;
    total.value = restult.data.total
  }else{
    ElMessage.error(restult.msg)
  }
}
// 通用提交处理
const handleSubmit = () => {
  if (mode.value === 'add') {
    handleAddSubmit()
  } else if (mode.value === 'edit') {
    handleEditSubmit()
  }
}
// 提交添加
const handleAddSubmit = async () => {
  try {
    const result = await addArticleCategory(formData.value);
    if (result.code === 1) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '添加失败');
    }
  } catch (error) {
    ElMessage.error('添加请求失败');
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const result = await updateArticleCategory(formData.value);
    if (result.code === 1) {
      ElMessage.success('更新成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新请求失败')
  }
}

// 打开添加对话框
const openAddDialog = () => {
  mode.value = 'add'
  formData.value = {
    id: null,
    categoryName: '',
    createTime: ''
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  mode.value = 'edit'
  formData.value = { ...row, createTime: new Date().toISOString().replace('T', ' ').substring(0, 19) }
  dialogVisible.value = true
}

// 打开详情对话框
const openViewDialog = (row) => {
  mode.value = 'view'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 模式映射配置
const modeMap = reactive({
  add: { title: '添加文章', submit: handleAddSubmit },
  edit: { title: '编辑文章', submit: handleEditSubmit },
  view: { title: '文章详情' }
})


const handleDelete = async (idOrRows) => {
  // 统一处理为数组
  let ids = []
  // 数据类型转换逻辑
  if (typeof idOrRows === 'number') {
    ids = [idOrRows]
  } else if (Array.isArray(idOrRows)) {
    ids = idOrRows.map(item => Number(item.id))
  } else {
    ids = selectedRows.value.map(item => Number(item.id))
  }

  try {
    await ElMessageBox.confirm('确定删除选中数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await deleteArticleCategory(ids)
    if (result.code === 1) {
      ElMessage.success('删除成功')
      // 清空选中项
      selectedRows.value = []
      search()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    console.log('取消删除')
  }
}

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}
</script>

<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="文章类型名称">
      <el-input v-model="formInline.categoryName" placeholder="请输入文章类型名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="openAddDialog">+添加文章类型</el-button>
      <el-button type="danger" @click="handleDelete">-批量删除</el-button>
    </el-form-item>
  </el-form>


  <el-table :data="tableData" border style="width: 100%"  @selection-change="val => selectedRows = val">
    <el-table-column type="selection"/>
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="categoryName" label="文章类型名称"/>
    <el-table-column prop="createTime" label="创建时间"/>
    <el-table-column label="操作" width="280px">
      <template #default="scope">
        <el-button type="warning" size="mini"  @click="openViewDialog(scope.row)">详情</el-button>
        <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  <!-- 通用对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="modeMap[mode].title"
      width="40%"
  >
    <el-form
        :model="formData"
        label-width="100px"
        :disabled="mode === 'view'"
    >
      <!-- 查看模式显示ID和创建时间 -->
      <template v-if="mode === 'view'">
        <el-form-item label="FM ID">
          <el-input v-model="formData.id" readonly />
        </el-form-item>
      </template>

      <!-- 公共字段 -->
      <el-form-item label="文章类型名称" prop="categoryName" :rules="formRules.categoryName">
        <el-input v-model="formData.categoryName" />
      </el-form-item>

      <!-- 在对话框的表单中修改这部分 -->
      <el-form-item label="创建时间" v-if="mode === 'view'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            readonly
            disabled
        />
      </el-form-item>

      <!-- 添加编辑时的时间字段（如果需要编辑时间） -->
      <el-form-item label="创建时间" v-else-if="mode === 'edit'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="创建时间" v-else-if="mode === 'add'">
        <el-date-picker
            v-model="formData.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
          v-if="mode !== 'view'"
          type="primary"
          @click="handleSubmit">确认
      </el-button>
    </template>
  </el-dialog>




  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                 :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                 layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                 @current-change="handleCurrentChange" />

</template>
<style scoped>
/* 全局边距调整 */
.demo-form-inline {
  margin-bottom: 20px;
}

/* 表单元素间距调整 */
.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
  margin-right: 10px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 按钮组间距 */
.el-button + .el-button {
  margin-left: 12px;
}

/* 表格调整 */
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 分页组件调整 */
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 对话框表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 上传组件调整 */
.el-upload {
  margin-top: 8px;
}

/* 对话框底部按钮间距 */
.el-dialog__footer .el-button:not(:last-child) {
  margin-right: 12px;
}

/* 操作列按钮紧凑布局 */
.el-table-column--operation .el-button {
  margin: 4px;
  padding: 7px 12px;
}

/* 时间选择器宽度 */
.el-date-editor {
  width: 100%;
}
</style>